Locations = new Meteor.Collection("locations");
Banks =  new Meteor.Collection("banks");
Atms =  new Meteor.Collection("atms");
AtmMap = null;
MapData = [];

// Map rendered
Session.setDefault('map_rendered', 0);

// User location
Session.setDefault('geo_user_location', null);

// Location No ATM
Session.setDefault('no_atm', 0);

// Set default lat and lng of location
Session.setDefault('lat_lng', '11.558818_104.917469');

Session.setDefault('has_scrollbar', 1);
//////// Other Function ///////
var getLocationByName = function (location) {
  return Locations.findOne({name: location});
};

// ID of currently selected location
Session.setDefault('location_id', null);
// ID of currently selected bank
Session.setDefault('bank_id', null);

// Subscribe to 'lists' collection on startup.
// Select a list once data has arrived.
var locationsHandle = Meteor.subscribe('locations', function () {
  if (!Session.get('location_id')) {
    //var defaultLocation = getLocationByName("Phnom Penh");
    var defaultLocation = getLocationByName("Kandal");
    if (defaultLocation) {
      Router.setLocation(defaultLocation._id);
      Session.set('location_id', defaultLocation._id);
      Session.setDefault('lat_lng', defaultLocation.lat + '_' + defaultLocation.lng);
    }
  }
});

var banksHandle = null;
// Always be subscribed to the todos for the selected list.
Deps.autorun(function () {
  var location_id = Session.get('location_id');
  if (location_id)
    bankHandle = Meteor.subscribe('Locations', location_id);
  else
    banksHandle = null;
});

////////////// Locations ///////////////
Template.locations.loading = function () {
  return !locationsHandle.ready();
};

Template.locations.locations = function () {
  return Locations.find({}, {sort: {name: 1}});
};
Template.locations.events({
  'mousedown .location': function(e) {
      Router.setLocation(this._id);
      Session.set('lat_lng', this.lat + "_" + this.lng);
      jQuery(".location-box-title > span").html("("+this.name+")");
      CustomScrollbarEvent.bankScrollbar(); // Enable Scroll
      if (AtmMap) {
         AtmMap.removeMarkers();
         AtmMapEvent.removePolyline();
      }
    },
  'click .location': function (e) {
    e.preventDefault();
  }
});
Template.locations.isDefaultSelect = function(selected) {
  return this.name === selected;
};
Template.locations.selected = function () {
  return Session.equals('location_id', this._id) ? 'selected' : '';
};
///////////// Banks //////////////
Template.banks.loading = function () {
  return banksHandle && !banksHandle.ready();
};

Template.banks.any_location_selected = function () {
  return !Session.equals('location_id', null);
};
Template.banks.banks = function () {
  var location_id = Session.get('location_id');
  if (!location_id)
    return {};
  var sel = {location_id: location_id};
  var banks = Banks.find(sel);
  var mapData = [];
  banks.forEach(function(bank){
    Session.set('mapData', null);
    var atms = Atms.find({bank_id: bank._id},{sort: {name: 1}});
    if (atms.count() > 0) {
      mapData.push(atms);
    }
  });
  if (mapData.length > 0 && Session.get('map_rendered') > 0) {
    generateATMOnMap(mapData);
  } else {
    centerMap(); // Move Map To Location
  }
  mapData = [];
  return banks;
};
Template.banks.events({
  'click .bank': function (){
    Session.set('bank_id', this._id);
    console.log(this._id);
    var atmData = [];
    atms = Atms.find({bank_id: this._id});
    console.log(atms.count());
    if (atms.count() > 0) {
      atmData.push(atms);
      generateATMOnMap(atmData);
      atmData = [];
    } else {
      if (AtmMap) {
         AtmMap.removeMarkers();
         AtmMapEvent.removePolyline();
      }

    } 
  }
});
Template.banks.selected = function () {
  return Session.equals('bank_id', this._id) ? 'selected' : '';
};

////////// Tracking selected location in URL //////////

var AtmsRouter = Backbone.Router.extend({
  routes: {
    ":location_id": "main"
  },
  main: function (location_id) {
    var oldLocation_id = Session.get("location_id");
    if (oldLocation_id !== location_id) {
      Session.set("location_id", location_id);
      //Session.set("tag_filter", null);
    }
  },
  setLocation: function (location_id) {
    this.navigate(location_id, true);
  }
});

Router = new AtmsRouter();

Meteor.startup(function () {
  Backbone.history.start({pushState: true});
});

///////////// Google Map Render /////////////
Template.maps.rendered = function() {
    //if (Session.get('map_rendered') === 0) {
      var latlng = getLatLng(Session.get('lat_lng'));
      AtmMap = new GMaps({
          div: '#mapCanvas',
          lat: latlng[0],
          lng: latlng[1]
        });
      Session.set('map_rendered', 1);
    //}
};

var generateATMOnMap = function (data) {
  if (AtmMap) {
      var latlng = getLatLng(Session.get('lat_lng'));
      var iconBase = 'images/';
      var aShadow = {
          url: iconBase + 'shadow50.png',
          /*anchor: new google.maps.Point(16, 34)*/
      };
      AtmMap.removeMarkers();
      AtmMapEvent.removePolyline();
      AtmMap.setCenter(latlng[0], latlng[1]);
      for (var i = 0; i < data.length; i++) {
      var atms = data[i];
      atms.forEach(function(atm) {
          AtmMap.addMarker({
             lat: atm.lat,
             lng: atm.lng,
             icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter_withshadow&chld=A|05a550|FFFFFF',
             infoWindow: {
                content: '<div class="info-window"><h2>'+ atm.name +'</h2><div class="photo-desc"><div class="photo"><img src="images/'+atm.photo+'"/></div><div class="desc">' + atm.address +'</div></div><div class="wrap-btn-route"><button class="btn btn-primary get-direction" onClick="AtmMapEvent.showDirection('+atm.lat+','+ atm.lng+')"><i class="icon-road icon-white"></i> Get direction</button></div></div>'
             }
          });
      });
    }
  }
  if (data.length > 0 && AtmMap) {
    AtmMap.fitZoom();
  }
};

var getLatLng = function(latLng) {
  return latLng.split('_');
};

var centerMap = function () {
  var latlng = getLatLng(Session.get('lat_lng'));
  var location = Locations.findOne({_id: Session.get('location_id')});
  if (AtmMap) {
    AtmMap.removeMarkers();
    AtmMap.addMarker ({
          lat: latlng[0],
          lng: latlng[1],
          infoWindow: {
            content: "<h2>"+ location.name +"</h2>"
          }
    });
    AtmMap.setZoom(9);
    AtmMap.setCenter(latlng[0], latlng[1]);
  }
};
Template.search.rendered = function() {
  console.log("search");
  jQuery("#searchATM").keyup(function() {
    var keyword = jQuery(this).val();
    if (keyword.length > 2) {
      var reg = RegExp(keyword, "i");
      atms = Atms.find({atm: reg});
      if (atms.count()) {
        generateATMOnMap([atms]);
      } else {
        AtmMapEvent.removePolyline();
        AtmMap.removeMarkers();
      }
    }
  });
};